package com.jin.crud.service.impl;

import com.jin.crud.bean.LoginBody;
import com.jin.crud.bean.LoginUser;
import com.jin.crud.bean.SysUser;
import com.jin.crud.common.code.ResultCode;
import com.jin.crud.common.exception.ResultException;
import com.jin.crud.common.utils.JwtUtils;
import com.jin.crud.common.utils.ServletUtils;
import com.jin.crud.common.utils.ip.IpUtils;
import com.jin.crud.dao.SysUserMapper;
import com.jin.crud.service.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author yuxuejin
 * @Date 2021/11/22 14:36
 * @Description:
 */
@Slf4j
@Service
public class SysLoginServiceImpl implements SysLoginService {

    //@Autowired
    //private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    JwtUtils jwtTokenUtil;

    @Override
    public String login(LoginBody loginBody) {

        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword()));
            //存储认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (Exception e) {
            log.info("", e);
            if (e instanceof BadCredentialsException) {
                throw new ResultException(ResultCode.USER_CREDENTIALS_ERROR.getCode(), ResultCode.USER_CREDENTIALS_ERROR.getMessage());
            } else {
                throw new ResultException(20211125, e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //生成token
        return jwtTokenUtil.generateAccessToken(loginUser);
        // 生成token
        //return tokenService.createToken(loginUser);
    }

    @Override
    public void  logout() {
        LoginUser loginUser = jwtTokenUtil.getUserDetailFromAuthContext();
        jwtTokenUtil.removeToken(loginUser.getUserId());
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(String userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(String.valueOf(System.currentTimeMillis()));
        userMapper.updateUser(sysUser);
    }
}
